package com.chengliang.bbs.handler;

import com.chengliang.bbs.entry.JSONResult;
import com.chengliang.bbs.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登陆验证成功的处理器
 * @author chengliang
 */
@Component
@Slf4j
public class SuccessHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        log.info("登录验证成功：{}",authentication.getPrincipal());
        String requestType = httpServletRequest.getHeader("X-Requested-With");
        //判断是否是ajax请求
        if(StringUtil.AJAX_REQUEST_TYPE.equals(requestType)){
            httpServletResponse.setContentType("application/json;charset=utf-8");
            PrintWriter out = httpServletResponse.getWriter();
            //验证成功跳转主页
            out.write(JSONResult.success().append("action","/").toString());
            out.flush();
            out.close();
        }else{
            //跳转主页
            httpServletResponse.sendRedirect("/");
        }
    }

}
